﻿using Microsoft.TeamFoundation.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using VisualStudioUtilities.MVC.Areas.Tfs.Models;

namespace VisualStudioUtilities.MVC.Areas.Tfs.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Tfs/Account/

        public ActionResult LogIn()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogIn(TfsLoginModel model)
        {
            var authenticated = false;
            if (ModelState.IsValid)
            {
                var credential = new NetworkCredential(model.UserName, model.Password, model.Domain);
                var tfs = default(TfsTeamProjectCollection);
                try
                {
                    tfs = new TfsTeamProjectCollection(new Uri(model.CollectionURL), credential);
                    tfs.EnsureAuthenticated();
                    authenticated = tfs.HasAuthenticated;
                }
                catch (Exception e)
                {
                    authenticated = false;
                }
                finally
                {
                    if (tfs != null)
                        tfs.Dispose();
                }

                if (!authenticated)
                {
                    ModelState.AddModelError("Password", "The user name or password provided is not correct.");
                }
            }

            if (authenticated && ModelState.IsValid)
            {
                Session[Constants.TfsLoginModelSessionKey] = model;
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }
    }
}
